package com.zwz.crawler.annualReports;


import com.zwz.constant.Constant;
import com.zwz.entity.EnterpriseAnnualReport;
import com.zwz.parse.JsonParserUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.jsoup.Connection;
import org.jsoup.Jsoup;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 企业年报信息的数据读取
 *
 */
@Slf4j
public class TungReports {


//    Cookie 自动维护

    // 登录方法示例,todo 待以后改写
    public static Map<String, String> refreshCookies() throws Exception {
//        try (CloseableHttpClient client = HttpClients.createDefault()) {
        HttpPost login = new HttpPost("https://user.tungee.com/login");
//            login.setEntity(new UrlEncodedFormEntity(List.of(
//                    new BasicNameValuePair("phone", "13800138000"),
//                    new BasicNameValuePair("password", "encrypted_pass")
//            )));

//            return client.execute(login, response -> {
//                return Arrays.stream(response.getHeaders("Set-Cookie"))
//                        .collect(Collectors.toMap(
//                                h -> h.getValue().split("=")[0],
//                                h -> h.getValue().split(";")[0]
//                        ));
//            });
//        }
    return  null;
    }









    public static List<EnterpriseAnnualReport> startTungReports( ) {
        // 请求参数
        String boundary = "----WebKitFormBoundaryEjgghMBMkO7Wg3BU";
        String url = "https://sales.tungee.com/api/cooperative/customer/search";

        // 构建 multipart 请求体
        String requestBody = buildMultipartBody(boundary);

        List<EnterpriseAnnualReport> res = null;

        try {
            Connection.Response response = Jsoup.connect(url)
                    .method(Connection.Method.POST)
                    .header("Content-Type", "multipart/form-data; boundary=" + boundary)
                    // 设置完整请求头
                    .header("authority", "sales.tungee.com")
                    .header("accept", "*/*")
                    .header("accept-encoding", "gzip, deflate, br, zstd")
                    .header("accept-language", "zh-CN,zh;q=0.9")
                    .header("cache-control", "no-cache")
//                    .header("cookie", "tx_pid=67864ea75f69e05d3b544ca7; __wpkreporterwid_=cc4a07fc-7bb9-40a4-96bc-2cbac34b658f; __last_enter_version=sales; _co_i=6805a5576eceb9637696f09d; _tx_uid=680701dddca941522b77e864; _tx_cid=6805a5576eceb9637696f09d; DISTINCT_ID=b84fe276-099f-4932-92b3-d54b92ae384b; _tx_sid=MTc0NTMwMTE0MzYyMjo4MmQ2OTQ5MTY0NjU2ODNmYjQ5MjlmMjc3NDg5ZDFlZg==; Hm_lvt_f2ee75449fc055cc4dbceb4fe403bea3=1745301094,1745302709; HMACCOUNT=B4E402DF057C895E; SecurityCenterDuId=ImFBSG15RzdPdVdPdCtsWnNGMFVuSXhVPSI.GujnjA.YBo4Zvc8vs4jgEmtioacknOQ9pE; tg_referrer_source=https%3A%2F%2Fuser.tungee.com%2F; acw_tc=1a0c399c17453774119646163e0075ab798fc34903e67c7d6c26b928bcee49; Hm_lpvt_f2ee75449fc055cc4dbceb4fe403bea3=1745378947; accountCenterSessionId=.eJwlz0FOwzAQheG7eN3FjMex3eygqdjQZFOElE00tscyURSkJAUE4u4EOMD79b0vNYukYeU3GbbXIQVVZ55WOaj1JaladU0p7WfEvnnauqYv_Qmgu7bj4_P5o324bO14V12u_dQ2Z-rH-6IOavgbEpPPHjGAULKUMmZvUTBJkJAdOiH2UYcEho0YE2N0jglAA0c4AoDLnpL3htkguUCcuYrO6FgBcUimgoTBgvGgrcFkRIPOQns5OZIdEgvPs0w75l3CLywvshZVb8tt_3dbZfmnWg-ushCtRAlHS0EMotZaff8A6oBUfw.GunwBA._2rz4r41oANU7jlGOoxKODaYTDI; doncusSessionId=eyJfZnJlc2giOmZhbHNlLCJ1c2VyX2lkIjoiNjgwNzAxZGRkY2E5NDE1MjJiNzdlODY0In0.GunwDw.MS6NpEOd0M2gQRZTT-x6XZ4BdC4")
                    .header("cookie", Constant.cookies)
                    .header("origin", "https://sales.tungee.com")
                    .header("pragma", "no-cache")
                    .header("priority", "u=1, i")
                    .header("referer", "https://sales.tungee.com/enterprise-details/577de19eadf21dc4/enterprise-information/bidding")
                    .header("sec-ch-ua", "\"Not;A=Brand\";v=\"24\", \"Chromium\";v=\"128\"")
                    .header("sec-ch-ua-mobile", "?0")
                    .header("sec-ch-ua-platform", "\"Windows\"")
                    .header("sec-fetch-dest", "empty")
                    .header("sec-fetch-mode", "cors")
                    .header("sec-fetch-site", "same-origin")
                    .header("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36")
                    .header("x-tonxis-pid", "67864ea75f69e05d3b544ca7")
                    // 关键配置
                    .ignoreContentType(true)
                    .maxBodySize(0)
                    .timeout(30000)
                    .requestBody(requestBody)
                    .execute();

           log.info("HTTP状态码: " + response.statusCode());
//           //log.info("响应内容:\n" + response.body());
            handleErrors(response);



            //解析
        res = JsonParserUtil.parseAnnualReport(response.body());



        } catch (IOException e) {
            System.err.println("请求异常: " + e.getMessage());
            e.printStackTrace();
        }

        return res;
    }

    private static String buildMultipartBody(String boundary) {
        StringBuilder body = new StringBuilder();

        // 添加 nameId 参数
        body.append("--").append(boundary).append("\r\n")
                .append("Content-Disposition: form-data; name=\"nameId\"\r\n\r\n")
                .append("577de19eadf21dc4\r\n");

        // 添加 begin 参数
        body.append("--").append(boundary).append("\r\n")
                .append("Content-Disposition: form-data; name=\"begin\"\r\n\r\n")
                .append("0\r\n");

        // 添加 end 参数
        body.append("--").append(boundary).append("\r\n")
                .append("Content-Disposition: form-data; name=\"end\"\r\n\r\n")
                .append("5\r\n");

        // 添加 filter 参数
        body.append("--").append(boundary).append("\r\n")
                .append("Content-Disposition: form-data; name=\"filter\"\r\n\r\n")
                .append("{}\r\n");

        // 结束边界
        body.append("--").append(boundary).append("--\r\n");


        //解析：


        return body.toString();
    }

    private static void handleErrors(Connection.Response response) {
        switch (response.statusCode()) {
            case 400:
                System.err.println("[参数错误] 请检查：");
                System.err.println("1. filter参数必须为有效JSON（当前值：{}）");
                System.err.println("2. begin/end分页值有效性");
                break;
            case 401:
                System.err.println("[认证过期] 需要：");
                System.err.println("1. 更新Cookie中的accountCenterSessionId");
                System.err.println("2. 检查请求签名（可能需要x-tonxis-signature头）");
                break;
            case 413:
                System.err.println("[请求过大] 建议：");
                System.err.println("1. 减少分页区间（end - begin <= 100）");
                break;
            case 500:
                System.err.println("[服务错误] 可能原因：");
                System.err.println("1. 请求体格式错误（检查boundary格式）");
                System.err.println("2. 服务器处理异常（稍后重试）");
                break;
        }
    }



}

